<template>
  <div class="category">
    <h3 class="title">课程分类</h3>
    <div class="toolbar">
      <el-button
        type="danger"
        size="small"
        icon="el-icon-plus"
        @click="showDialog = true"
      >
        添加
      </el-button>
    </div>
    <xu-table :data="tableData" :options="tableOptions" :pager="pager" />

    <el-dialog :title="title" :visible.sync="showDialog">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <div class="footer" slot="footer">
        <el-button type="default" size="small" @click="closeDialog">
          取消
        </el-button>
        <el-button type="primary" size="small" @click="submit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import table from '../../../mixins/table'
import { CategoryActionsEnum } from '../../../_/vue/store/category'
export default {
  mixins: [table],
  data () {
    return {
      id: '',
      title: '添加分类',
      showDialog: false,
      tableOptions: [
        { attrs: { label: 'ID', prop: 'id', width: '80px', align: 'center' } },
        { attrs: { label: '名称', prop: 'name' } },
        {
          attrs: { label: '操作', prop: 'opt', width: '120px', align: 'center' },
          buttons: [
            { label: '编辑', icon: 'el-icon-edit', type: 'primary', click: this.editRow },
            { label: '删除', icon: 'el-icon-delete', type: 'popover', click: this.deleteRow }
          ]
        }
      ],
      form: {
        name: ''
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      }
    }
  },
  methods: {
    ...mapActions({
      list: CategoryActionsEnum.LIST,
      edit: CategoryActionsEnum.EDIT,
      save: CategoryActionsEnum.SAVE,
      store: CategoryActionsEnum.STORE,
      delete: CategoryActionsEnum.DELETE
    }),
    closeDialog () {
      this.form.name = ''
      this.id = ''
      this.showDialog = false
    },
    editRow ({ row }) {
      this.id = row.id
      this.form.name = row.name
      this.showDialog = true
    },
    deleteRow ({ row }) {
      this.delete({ ids: [row.id] })
      this.getData()
    },
    submit () {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.id) {
            this.save({ id: this.id, data: this.form })
          } else {
            this.store(this.form)
          }
          this.form.name = ''
          this.showDialog = false
          this.id = ''
          this.getData()
        }
        return false
      })
    }
  }
}
</script>
